package com.winit.openapi.fsp.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.query.filter.SearchFilterHelper;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.fsp.spi.interest.InterestService;
import com.winit.fsp.spi.interest.command.QueryInterestCommand;
import com.winit.fsp.spi.interest.vo.Interest;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 贷款交易明细
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * hui.li2 	1.0  		2015-4-7 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/fsp/interest")
public class InterestController extends BaseController {

    @Resource
    private InterestService interestService;

    /**
     * 分页查询利息单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     * @author LH
     * @throws ParseException
     * @date 2015-4-7
     */
    @RequestMapping(value = "/pageQueryInterest")
    public String pageQueryInterest(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg)
                                                                                                                   throws ParseException {
        Object obj = requestMsg.getData();
        QueryInterestCommand command = new QueryInterestCommand();
        CommandContext ctx = CommandContext.getContext();
        Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validpageParams(json);
            try {
                command = JSONObject.toJavaObject(json, QueryInterestCommand.class);
                Searchable searchable = buildSearchPageParams(json);
                searchable.addSort(new Sort(Direction.DESC, "CREATED"));
                if (StringUtils.isNotEmpty(command.getLoanNo())) {
                    searchable.and(SearchFilterHelper.newCondition("LOAN_NO", SearchOperator.like, command.getLoanNo()));
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                if (null != command.getStartDate()) {
                    searchable.and(SearchFilterHelper.newCondition("CREATED",
                        SearchOperator.gte,
                        sdf.parse(sdf1.format(command.getStartDate()) + " 00:00:00")));
                }
                if (null != command.getEndDate()) {
                    searchable.and(SearchFilterHelper.newCondition("CREATED",
                        SearchOperator.lte,
                        sdf.parse(sdf1.format(command.getEndDate()) + " 23:59:59")));
                }
                if (null != bpartner.getcBpartnerId()) {
                    searchable.and(SearchFilterHelper.newCondition("PARTNER_ID",
                        SearchOperator.eq,
                        bpartner.getcBpartnerId()));
                }
                command.setSearchable(searchable);
                command.setCtx(ctx);
            } catch (SPIException e) {
                throw new SPIException("javaBean 转换错误");
            }
            Page<Interest> page = interestService.pageQueryInterest(command);
            if (page != null) {
                Map<String, Object> pageMap = new HashMap<String, Object>();
                pageMap.put("pageNo", page.getPageable().getPageNumber() + 1);
                pageMap.put("pageSize", page.getPageable().getPageSize());
                pageMap.put("totalCount", page.getTotalElements());

                Map<String, Object> data = new HashMap<String, Object>();
                data.put("list", page.getContent());
                data.put("pageParams", pageMap);
                responseMsg.setData(data);
            }

        } else {
            throw new SPIException("json 格式错误");
        }
        return SUCCESS;
    }

    private Searchable buildSearchPageParams(JSONObject json) {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        // pageParams
        if (json != null && json.containsKey("pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");
            // pageNo
            if (pageParams.containsKey("pageNo")) {
                pageNo = pageParams.getInteger("pageNo");
            }
            // pageSize
            if (pageParams.containsKey("pageSize")) {
                pageSize = pageParams.getInteger("pageSize");
            }
        }
        Searchable search = Searchable.newSearchable();
        search.setPage(pageNo - 1, pageSize);
        search.addSort(new Sort(Direction.DESC, "CREATED"));
        return search;
    }

    private void validpageParams(JSONObject json) {
        // pageParams
        if (json.containsKey("pageParams")) {
            Object obj = json.get("pageParams");
            if (obj instanceof JSONObject) {
                JSONObject pageParams = (JSONObject) obj;
                // pageNo
                ValidateUtil.validInteger(pageParams, "pageNo");
                // pageSize
                ValidateUtil.validInteger(pageParams, "pageSize");
                if (pageParams.containsKey("pageNo")) {
                    int pageNo = pageParams.getInteger("pageNo");
                    if (pageNo < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                    }
                }
                if (pageParams.containsKey("pageSize")) {
                    int pageSize = pageParams.getInteger("pageSize");
                    if (pageSize < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                    }
                }
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageParams");
            }
        }
    }
}
